package com.capinfo.accumulation.web.controller.collection;

import com.capinfo.accumulation.model.collection.Company;
import com.capinfo.accumulation.model.collection.Payininfo;
import com.capinfo.accumulation.parameter.collection.CompanyParameter;
import com.capinfo.accumulation.parameter.collection.PayininfoParameter;
import com.capinfo.accumulation.service.collection.PayininfoService;
import com.capinfo.accumulation.web.Constants;
import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.commons.project.parameter.security.SystemResourceParameter;
import com.capinfo.commons.project.utils.JsonUtils;
import com.capinfo.commons.project.web.controller.manage.region.RegionManageController;
import com.capinfo.framework.model.dictionary.Dictionary;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.util.ControllerUtils;
import com.capinfo.framework.web.util.WebRequestUtils;
import com.capinfo.framework.web.view.model.DataListViewModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Logger;

/**
 * Created by wcj on 2017/10/24.
 */
@Controller
@RequestMapping("/business/collection/payininfo")
public class PayininfoController extends CommonsDataManageController<PayininfoParameter, Payininfo> {
    private static final Log logger = LogFactory.getLog(PayininfoController.class);
//    @Autowired
    private PayininfoService payininfoService;
    @Override
    public CommonsDataOperationService<Payininfo, PayininfoParameter> getCommonsDataOperationService() {
        System.out.println(payininfoService.toString());
        return payininfoService;
    }
    //查询待核定汇缴信息
    //添加字典项
    @Override
    public Map<String, Object> search(PayininfoParameter parameter) {

        Map<String, Object> viewModel = ControllerUtils.buildViewModel(parameter);
        Set<Dictionary> siteList = payininfoService.getDictionariesBySortName("缴存网点");
        viewModel.put("siteList", siteList);
        Set<Dictionary> hdItemList = payininfoService.getDictionariesBySortName("公积金账户类型");
        viewModel.put("hdItemList",hdItemList);
        return  viewModel;
    }

    @RequestMapping("/search_payinfo.shtml")

    public void getCompanyAccount(NativeWebRequest request, PayininfoParameter parameter,OutputStream stream){
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);
        Map map = new HashMap<String, Object>();
        map.put("uname", payininfoService.getCompanyAccount(parameter).getUnitName());
        try {
            IOUtils.outputByStream(stream, JsonUtils.toGlobleJsonObject(map).toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LogUtils.debugException(logger,e);
        }

    }

    @Override
    protected Map<String, Object> formAfterInvoke(NativeWebRequest request, PayininfoParameter parameter, Map<String, Object> viewModel) {
        Set<Dictionary> siteList = payininfoService.getDictionariesBySortName("缴存网点");
        viewModel.put("siteList", siteList);
        Set<Dictionary> hdItemList = payininfoService.getDictionariesBySortName("公积金账户类型");
        viewModel.put("hdItemList",hdItemList);
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyyMM" );
        String str = sdf.format(new Date());
        viewModel.put("curym",str);
        viewModel.put("payinfo_id",parameter.getEntity().getId());
        viewModel.put("hdtype",parameter.getEntity().getVerificationOptions());
        return super.formAfterInvoke(request, parameter, viewModel);

    }
    @RequestMapping("/build_payininfo_inventory.shtml")
    public void buildPainfo(NativeWebRequest request, PayininfoParameter parameter){
        WebRequestUtils.setContentType(request, "application/json;charset=UTF-8");

        Object nativeResponse = request.getNativeResponse();
        if (nativeResponse instanceof ServletResponse) {

            HttpServletResponse response = (HttpServletResponse) nativeResponse;
            OutputStream stream = null;
            SystemUser user  = (SystemUser)WebRequestUtils.retrieveSessionAttribute( request, com.capinfo.framework.web.Constants.ADMIN_ATTRIBUTE_KEY);
            try {
                stream = response.getOutputStream();
                boolean b = payininfoService.buildPayininfoQc(parameter, user.getLogonName());
                if (b) {
                    JSONObject json = new JSONObject();
                    //json.put("id", entity.getId());
                    json.put("result", "success");

                    IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
                } else {

                    IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    @RequestMapping("/search_payinfounchcked.shtml")
    @ResponseBody
    public void getPayinfoUncheck(NativeWebRequest request, PayininfoParameter parameter,OutputStream stream){
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);
        List<Payininfo> payininfos = payininfoService.searchPayinfouncheck(parameter);
//        Map map =new HashMap<String,Object>();
//        map.put("total",payininfos.size());
//        map.put("rows",payininfos);
        int count=0;
        String companyAccount=null;
        double amount=0l;
        long num=0l;
        if (payininfos!=null&&payininfos.size()>0){
             count=payininfos.size();
            for (Payininfo payininfo:payininfos){
                companyAccount=payininfo.getCompanyAccount();
                   amount+=payininfo.getRemitAmount().doubleValue();
                   num+=payininfo.getRemitNumber();
            }

        }

//        JsonConfig jsonConfig = new JsonConfig();
//        jsonConfig.setExcludes(new String[]{"companyAccountFund","payinitems"});//除去emps属性
        Map map =new HashMap<String,Object>();
        map.put("count",count);
        map.put("amount",amount);
        map.put("num",num);
        map.put("account",companyAccount);
        try {
            IOUtils.outputByStream(stream, JsonUtils.toGlobleJsonObject(map).toString().getBytes("UTF-8"));
           // IOUtils.outputByStream(stream, JSONObject.fromObject(map,jsonConfig).toString().getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            LogUtils.debugException(logger,e);
        }

    }

    @RequestMapping("/payinfo_confirm.shtml")
    public void confirm(NativeWebRequest request, PayininfoParameter parameter, OutputStream stream) throws UnsupportedEncodingException{
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

          Boolean token = payininfoService.confirm(parameter);
        if (token) {
            JSONObject json = new JSONObject();
            //json.put("id", parameter.getEntity().getId());
            json.put("result", "success");
            IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
        } else {

            IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
        }
    }

    @RequestMapping("/payinfo_cancel.shtml")
    public void cancel(NativeWebRequest request, PayininfoParameter parameter, OutputStream stream) throws UnsupportedEncodingException{
        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);

        Boolean token = payininfoService.cancel(parameter);
        if (token) {
            JSONObject json = new JSONObject();
            //json.put("id", parameter.getEntity().getId());
            json.put("result", "success");
            IOUtils.outputByStream(stream, json.toString().getBytes("UTF-8"));
        } else {

            IOUtils.outputByStream(stream, Boolean.FALSE.toString().getBytes());
        }

    }


}
